import socket
import threading
import time
import sys


class SocketClient:
    def __init__(self, host='127.0.0.1', port=8888):
        self.host = host
        self.port = port
        self.client_socket = None
        self.running = False
        self.receive_thread = None

    def connect(self):
        """连接到服务器"""
        try:
            self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.client_socket.connect((self.host, self.port))
            print(f"成功连接到服务器 {self.host}:{self.port}")
            return True
        except Exception as e:
            print(f"连接失败: {e}")
            return False

    def start_receiving(self):
        """启动接收线程"""
        if not self.client_socket:
            print("未连接到服务器，请先调用connect()")
            return

        self.running = True
        self.receive_thread = threading.Thread(target=self._receive_data)
        self.receive_thread.daemon = True  # 设置为守护线程，主程序退出时自动结束
        self.receive_thread.start()
        print("已启动接收线程")

    def _receive_data(self):
        """接收数据的线程函数"""
        while self.running:
            try:
                # 接收数据（最大1024字节）
                data = self.client_socket.recv(1024)
                if not data:
                    # 服务器关闭连接
                    print("服务器断开连接")
                    self.stop()
                    break

                # 解码并处理数据
                message = data.decode('utf-8')
                self.process_message(message)

            except ConnectionResetError:
                print("连接被服务器重置")
                self.stop()
                break
            except Exception as e:
                print(f"接收错误: {e}")
                self.stop()
                break

    def process_message(self, message):
        """处理接收到的消息（可自定义）"""
        # 这里只是简单打印，你可以根据需要扩展功能
        print(f"收到服务器消息: {message}")

    def send_message(self, message):
        """向服务器发送消息"""
        if not self.client_socket:
            print("未连接到服务器")
            return

        try:
            self.client_socket.sendall(message.encode('utf-8'))
            print(f"已发送: {message}")
        except Exception as e:
            print(f"发送失败: {e}")

    def stop(self):
        """停止客户端"""
        self.running = False
        if self.client_socket:
            try:
                self.client_socket.close()
            except:
                pass
            self.client_socket = None
        print("客户端已停止")


# 使用示例
if __name__ == "__main__":
    # 创建客户端实例
    client = SocketClient('127.0.0.1', 8888)

    # 连接到服务器
    if client.connect():
        # 启动接收线程
        client.start_receiving()

        try:
            # 主线程继续工作（这里模拟发送消息）
            while client.running:
                # 获取用户输入
                message = input("输入要发送的消息 (输入 'exit' 退出): ")

                if message.lower() == 'exit':
                    break

                # 发送消息
                client.send_message(message)

                # 短暂暂停，避免CPU占用过高
                time.sleep(0.1)

        except KeyboardInterrupt:
            print("\n用户中断程序")
        finally:
            # 清理资源
            client.stop()
            sys.exit(0)